package org.example.listener;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.User;
import org.example.domain.esdomain.UserIndex;
import org.example.mapper.UserMapper;
import org.example.repository.UserRepository;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import static org.example.constant.mqConstant.ADDUSER_QUEUE;
import static org.example.constant.mqConstant.EDITUSER_QUEUQ;

/**
 * 监听用户信息改变
 */
@Slf4j
@Component
public class listenerMQ {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Autowired
    private UserRepository userRepository;

    /**
     * 监听新增用户
     */
    @RabbitListener(queues = ADDUSER_QUEUE)
    public void listenerAddUser(String userId) {
        //查询用户
        User user = userMapper.selectById(userId);
        if (user != null) {
            //索引库添加用户
            User save = restTemplate.save(user);
            log.info("监听到新增用户到索引库user:" + JSONUtil.toJsonStr(save));
        }
    }

    /**
     * 监听修改用户
     */
    @RabbitListener(queues = EDITUSER_QUEUQ)
    public void listenerEditUser(String userId) {
        //查询用户
        User user = userMapper.selectById(userId);
        if (user != null) {
            //索引库添加用户
            UserIndex save = userRepository.save(new UserIndex(user));
            log.info("监听到新增用户到索引库user:" + JSONUtil.toJsonStr(save));
        }
    }
}
